package controller

import (
	"fileshare/conf"
	"fileshare/controller/server"
	"fileshare/controller/tools"
	"fileshare/utils"
	"math/rand"
	"net/http"
	"path/filepath"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
)

/**
* @program: fileshare
*
* @description:文件上传
*
* @author: Koco.Allien
*
* @create: 2020-04-05 20:52
**/

func UploadController(c *gin.Context) {
	aid := tools.GatQuery(c, "active", 1)
	folderid := c.Query("folderid")
	utils.MsgToLog("上传文件的页面:active:", aid, "文件夹:"+folderid)

	if folderid == "" {
		folderid = "1"
	}

	data, _, _ := tools.StartDate(c, "文件上传", aid)

	data["folderid"] = folderid
	c.HTML(http.StatusOK, "upload.html", data)
}

func UploadControllerPost(c *gin.Context) {
	aid := tools.GatQuery(c, "active", 1)

	data, user, ok := tools.StartDate(c, "文件上传", aid)
	if !ok {
		user.ID = 1
	}

	//得到文件的分享给谁
	if aid > 1 {
		aid = user.ID
	}
	utils.MsgToLog("上传文件的页面UploadControllerPost 文件给谁:", aid)
	// 处理文件
	folderid := c.PostForm("folderid") //文件夹的id信息

	fid, err := strconv.Atoi(folderid)
	if err != nil || fid <= 0 {
		data["error"] = "请求参数有误"
		data["folderid"] = folderid
		c.HTML(http.StatusOK, "upload.html", data)
	} else {

		f, _ := c.FormFile("file")
		rand.Seed(time.Now().Unix())
		fpath := conf.Cfg.Key("filepath").String()     //文件存储的路径
		encrypt, err := conf.Cfg.Key("encrypt").Bool() //文件加密
		if err != nil {
			encrypt = false
		}
		if encrypt {
			fpath = filepath.Join(fpath, strconv.Itoa(rand.Int())) //去掉文件的类型
		} else {
			fpath = filepath.Join(fpath, strconv.Itoa(rand.Int())+filepath.Ext(f.Filename))
		}
		_, fname := filepath.Split(f.Filename)
		server.SaveFileToDB(user.ID, fname, fpath, aid, fid, false)
		c.SaveUploadedFile(f, fpath)

		utils.LOGToLog("上传文件的页面:", user.ID, "文件名称:", f.Filename, "文件路径:", fpath)
		data["error"] = "文件路径:" + fpath
		data["folderid"] = folderid
		c.HTML(http.StatusOK, "upload.html", data)
	}
}
